package com.ts.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ts.content.constants.RedisKeys;
import com.ts.content.entity.FollowEntity;
import com.ts.content.mapper.FollowMapper;
import com.ts.content.service.FollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper,FollowEntity> implements FollowService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void follower(Integer userId, Integer followUid){
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();

        //获取关注者的key和被关注者的key
        String followKey = String.format(RedisKeys.USER_FOLLOWER, userId);
        String fansKey = String.format(RedisKeys.USER_FANS, followUid);

        //去redis中查询关注者的信息
        Long rank = zSetOperations.rank(fansKey, userId.toString());
        //没有关注，准备关注
        if (rank == null){
            //关注者列表加一
            zSetOperations.add(followKey,followUid.toString(),System.currentTimeMillis());
            //被关注者列表加一
            zSetOperations.add(fansKey,userId.toString(),System.currentTimeMillis());
        }else {
            //删除关注者
            zSetOperations.remove(followKey,followUid.toString());
            //删除粉丝
            zSetOperations.remove(fansKey,userId.toString());
        }

    }

    //判断当前用户是否对帖子用户关注了
    @Override
    public Boolean isFollow(Integer userId, Integer followUid){
        String followKey = String.format(RedisKeys.USER_FOLLOWER, userId);
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        Long rank = zSetOperations.rank(followKey, followUid.toString());
        if (rank == null){
            return false;
        }
        return true;
    }

}
